/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */
/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-08-30     RealThread   first version
 */

#include <rtthread.h>
#include <board.h>
#include <drv_common.h>
#include <rtdevice.h>
#include "bootloader.h"

extern void show_reset_form_wdt(void);
RT_WEAK void rt_hw_board_init()
{
    // USD->eopb0 = 0;//片上 SRAM 64K 字节
    SCB->VTOR = FLASH_APP_ADDR;
    // USD->eopb0 = 1;//片上 SRAM 16K 字节
    // USD->eopb0 = 2;//片上 SRAM 64K 字节
    // USD->eopb0 = 3;//片上 SRAM 32K 字节
    // SCB->VTOR = 0x08002400;
    extern void hw_board_init(char *clock_src, int32_t clock_src_freq, int32_t clock_target_freq);

    /* Heap initialization */
#if defined(RT_USING_HEAP)
    rt_system_heap_init((void *)HEAP_BEGIN, (void *)HEAP_END);
#endif

    hw_board_init(BSP_CLOCK_SOURCE, BSP_CLOCK_SOURCE_FREQ_MHZ, BSP_CLOCK_SYSTEM_FREQ_MHZ);

     show_reset_form_wdt();
    /* Set the shell console output device */
    // #if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
    //     rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
    // #endif

    /* Board underlying hardware initialization */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

    /* Set the shell console output device */
    /* serial v2 needs scheduler to handle tx-blocking while USING_DMA */
    /* so before scheduler start don't use consol */

}

#define DBG_TAG "wdt"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

bool wdt_need_alive = true;
rt_device_t wdt_dev=RT_NULL;
void rt_hw_cpu_reset(void)
{
    // rt_kprintf("System reboot...\n");
    // SCB->VTOR = FLASH_BASE;
    timer_t timeout=0;
    wdt_need_alive = false;
    rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    LOG_W("System will reboot in %d ms...\n", timeout);
}
void keep_wdt_alive(void)
{
    if(wdt_need_alive)
    {
        rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_KEEPALIVE, RT_NULL);
    }
}
void start_wdt(void)
{
    rt_err_t ret = RT_EOK;
    wdt_dev = rt_device_find("wdt");
    rt_uint32_t timeout = 50;
    if (!wdt_dev)
    {
        LOG_E("can't find wdt device\n");
        return;
    }
    ret = rt_device_init(wdt_dev);
    if (ret != RT_EOK)
    {
        LOG_E("wdt device init failed\n");
        return;
    }
    ret = rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_START, &timeout);
    rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
    if (ret != RT_EOK)
    {
        LOG_E("wdt set timeout failed\n");
        return;
    }
    rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    LOG_I("wdt start, timeout = %d ms\n", timeout);
    // rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
}
